package com.tensai.ext.wechat.service.impl;

import com.tensai.ext.wechat.entity.WeChatConfig;
import com.tensai.ext.wechat.service.IWeChatBase;
import com.tensai.ext.wechat.utils.AccessToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 微信操作基础Service
 * @author kissy
 */
@Slf4j
@Service
public class WeChatBase implements IWeChatBase {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获得微信 AccessToken
     * access_token是公众号的全局唯一接口调用凭据，公众号调用各接口时都需使用access_token。
     * 开发者需要access_token的有效期目前为2个小时，需定时刷新，重复获取将导致上次获取的access_token失效。
     * （此处我是把token存在Redis里面了）
     */
    @Cacheable(key = "'WeChat:_AccessToken:'+#weChatConfig.code", value = "2_hours")
    @Override
    public AccessToken getWXToken(WeChatConfig weChatConfig) {
        String appId = weChatConfig.getAppId();
        String appSecret = weChatConfig.getAppSecret();
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        ResponseEntity<AccessToken> exchange = getRestTemplate().exchange(tokenUrl, HttpMethod.GET, new HttpEntity<String>(null, new HttpHeaders()), AccessToken.class);
        return exchange.getBody();
    }

    public RestTemplate getRestTemplate() {
        return this.restTemplate;
    }

}
